import axios,{AxiosRequestConfig,AxiosError} from "axios";
import type {Response} from "./types";

import router from '@/router'

const service = axios.create({
    baseURL: import.meta.env.APP_BASE_URL, // url = base url + request url
});

service.interceptors.request.use(
    (config:AxiosRequestConfig) => {
        config.headers = {
            ...config.headers,
            'Authorization': 'Bearer ' + localStorage.getItem('token')
        }
        return config;
    },
    (error: AxiosError) => {
        return Promise.reject(error);
    }
);

service.interceptors.response.use(
    (response:AxiosResponse<Response>) => {
        const res = response.data;
        if (res.code === 200) {
            return Promise.reject(new Error(res.message || 'Error'));
        }},
    (error:AxiosError) => {
        return Promise.reject(error);
    }
）
